package com.woniuxy.company5.security;

import cn.hutool.core.util.StrUtil;
import com.woniuxy.company5.util.JwtUtils;
import com.woniuxy.company5.util.RedisCache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：fengSir
 * @date ：Created By 2022-12-02 10:59
 * @description ：TODO
 */

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //得到请求头中的token
        String token = request.getHeader("Authorization");
        //判断token是否为空
        if (StrUtil.isEmptyOrUndefined(token)) {
            filterChain.doFilter(request,response);
            return;
        }
        //判断是否合法
        Claims claims = jwtUtils.getClaimsByToken(token);
        if (claims == null) {
            throw new JwtException("不合法的token");
        }
        //判断是否过期
        boolean tokenExpired = jwtUtils.isTokenExpired(claims);
        if (tokenExpired) {
            throw new JwtException("token已过期");
        }
        //能走到这个位置，说明token是有效的
        String username = claims.getSubject();
        LoginUser user = (LoginUser) userDetailsService.loadUserByUsername(username);

        LoginUser loginUser = (LoginUser) redisCache.getCacheObject("rbac:" + username);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
